import store from '@/store'
import config from './config'
import { getToken, removeToken } from '@/utils/auth'
import errorCode from '@/utils/errorCode'
import { toast, showConfirm, tansParams } from '@/utils/common'
import moment from "moment"
import qs from "qs"
import func from './func.js'
let timeout = 60000
const baseUrl = config.baseUrl
const isEncrypt = false
var headers = {
	"content-type": "application/x-www-form-urlencoded",
	"api-name":"unionid"
}
function formatData(data) {
	const options = {
		data: data
	}
	if (JSON.stringify(options.data) !== '{}') { //将post请求参数变为字符串，json数组只处理一层  
		let res = []
		for (let key in options.data) {
			if ('object' == typeof(options.data[key])) {
				if (!(options.data[key] instanceof Array)) { //对象就直接转为字符串  
					res.push(encodeURIComponent(key) + '=' + encodeURIComponent(JSON.stringify(options.data[key])))
				} else { //数组处理  
					for (let i = 0; i < options.data[key].length; i++) { //  
						res.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(options.data[key][i]))
					}
				}
			} else {
				res.push(encodeURIComponent(key) + '=' + encodeURIComponent(options.data[key]))
			}
		}
		return res.join("&")
	}
}

const request = config => {
	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	const hasToken = (config.header || {}).hasToken
	config.header = config.header || {}
	config.header = { ...headers, ...config.header }

	if (getToken() && !isToken && hasToken !== false) {
		config.header['api-token'] =  getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}
	// func.consoleLog('请求开始时间=>',moment().format("YYYY-MM-DD HH:mm:ss SSSS"))

	return new Promise((resolve, reject) => {

		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.url.indexOf('http') == 0 ? config.url : (baseUrl + config.url),
				data: formatData(config.data),
				header: config.header,
				// dataType: 'json'

			}).then(response => {
				
				let [error, res] = response

				if (error) {
					func.consoleLog(response)
					
					toast('后端接口连接异常')
					reject('后端接口连接异常')
					return
				}
				
 
	 

				const code = res.data.code || 200
				const msg = errorCode[code] || res.data.info || errorCode['default']
				
				if (code === 401 || msg.indexOf('登录认证不能为空')>-1 || msg.indexOf('用户还没有注册')>-1) {
					store.commit('SET_LOGIN', false)
					store.commit("SET_INFO",{})
					removeToken()
					const showToLogin = store.state.setting.showLogin
					 
					if(!showToLogin) {
						store.commit("setShowLogin",true)
						uni.reLaunch({
							url:"/pages/login/index"
						})
					}
					reject(msg)	 
					// reject('无效的会话，或者会话已过期，请重新登录。')
				} else if (code === 500) {
					setTimeout(()=>{
						toast(msg)
					},500)
					
					reject(msg)
				} else if (code === 0) {
					setTimeout(()=>{
						toast(msg)
					},500)
					reject(msg)
				} else if (code !== 1 && (code !== 600)) {
					setTimeout(()=>{
						toast(msg)
					},500)
					reject(code)
				}
				 
				const returnData = decodeData(res)
				// func.consoleLog('请求结束时间=>',moment().format("YYYY-MM-DD HH:mm:ss SSSS"))
				resolve(returnData)
			})
			.catch(error => {
				let { message } = error
				if (message === 'Network Error') {
					message = '后端接口连接异常'
				} else if (message.includes('timeout')) {
					message = '系统接口请求超时'
				} else if (message.includes('Request failed with status code')) {
					message = '系统接口' + message.substr(message.length - 3) + '异常'
				}
				func.consoleLog('请求url=>',config.url)
				func.consoleLog('请求参数=>',config.data || '')
				func.consoleLog('错误信息=>',error)
			 
				setTimeout(()=>{
					toast(message)
				},500)
				reject(error)
			})
	})
}

function decodeData(res) {
	var returnData = res.data
	if (res.data.flag) {
		var decryptDataStr
		if (res.data.type == 1) {
			decryptDataStr = decryptSm2(res.data.data.slice(2))
		} else {
			decryptDataStr = decrypt(encodeURIComponent(res.data.data))
		}
		var decryptData
		try {
			decryptData = JSON.parse(decryptDataStr)
		} catch (e) {
			func.consoleLog('JSON字符串解析错误', e)
		}
		if (res.data.total) {
			returnData.rows = decryptData || []
		} else {
			returnData.data = decryptData
		}
	} else {
		returnData = res.data
	}
	return returnData
}
export default request